package com.drojian.operator;

import org.junit.Test;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 这里会报错，必须要在activity中执行，因为下面有AndroidSchedulers.mainThread()
 */
public class ToolOperator {
    @Test
    public void Test1() {
        System.out.println("======================");
        ToolOperator operator = new ToolOperator();
        operator.Test2();
        System.out.println("======================");
    }

    Observer observer = new Observer<Object>() {
        @Override
        public void onSubscribe(Disposable d) {
            System.out.println("onSubscribe:" + d + Thread.currentThread());
        }

        @Override
        public void onNext(Object o) {
            System.out.println("onNext:" + o + Thread.currentThread());
        }

        @Override
        public void onError(Throwable e) {
            System.out.println("onError:" + e + Thread.currentThread());
        }

        @Override
        public void onComplete() {
            System.out.println("onComplete:" + Thread.currentThread());
        }
    };

    public void Test2() {
        //默认全部都在主线程
        Observable.create(new ObservableOnSubscribe<Object>() {
                    @Override
                    public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                        emitter.onNext("aaa");
                        emitter.onNext("aaa");
                        emitter.onComplete();
                        System.out.println(Thread.currentThread());
                    }
                    //subscribeOn主要是上面发送事件所在线程
                }).subscribeOn(Schedulers.newThread())
                //只让耗时操作在子线程，后面的还在主线程中执行
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }
}
